<template>
  <div id="communityBuildingList" v-cloak>
    <el-container>
      <el-aside width="200px">
        <buildingTree ref="building_tree" @treeNode-click="treeNodeClick"></buildingTree>
      </el-aside>
      <el-main id="el-main">
        <div>
          <!--工具条-->
          <div name="searchColums" id="searchColums">
            <el-form :inline="true" :model="filters" size="small" ref="filters" class="searchForm">
              <el-form-item class="el-form-item" label="姓名">
                <el-input v-model="filters.name" name="name" auto-complete="off" placeholder="请输入姓名"></el-input>
              </el-form-item>
              <el-form-item class="el-form-item" label="手机号">
                <el-input v-model="filters.phone" name="phone" auto-complete="off" placeholder="请输入手机号"></el-input>
              </el-form-item>
              <span class="bth_search">
                <el-form-item>
                  <el-button type="success" icon="el-icon-search" v-on:click="getCommunityBuildings(true)">查询</el-button>
                </el-form-item>
                <el-form-item>
                  <el-button icon="el-icon-refresh" @click="resetSearchForm('filters')">重置</el-button>
                </el-form-item>
              </span>
            </el-form>
          </div>
          <!--toolbar-->
          <el-row id="toolbar" v-if="edit_authority">
            <el-col :span="24">
              <div class="grid-content bg-purple-light">
                <el-button type="primary" size="mini" icon="el-icon-edit" :disabled="addDisabled" @click="handleAdd">新增</el-button>
                <el-button type="primary" size="mini" @click="batchRemove" :disabled="this.sels.length===0" icon="el-icon-delete">批量删除</el-button>
                <el-button type="primary" size="mini" @click="templeteDown" icon="el-icon-download">模板下载</el-button>
                <el-button type="primary" size="mini" @click="templeteUp" :disabled="importDisabled" icon="el-icon-upload">导入</el-button>
              </div>
            </el-col>
          </el-row>

          <!--列表-->
          <el-table :data="communityBuildings" id="datagrid" empty-text=" " height="410" border stripe size="mini" :header-row-class-name="headStyle" highlight-current-row v-loading="listLoading" :row-class-name="tableRowClassName" @sort-change="handleSortChange" @selection-change="selsChange" style="width: 100%;">
            <el-table-column type="selection" width="45"></el-table-column>
            <el-table-column prop="index" :formatter="index_formatter" label="序号" width="60"></el-table-column>
            <el-table-column prop="name" label="姓名" width="120" show-overflow-tooltip></el-table-column>
            <el-table-column prop="phone" label="手机号" width="160" show-overflow-tooltip></el-table-column>
            <el-table-column prop="sexName" label="性别" width="60" show-overflow-tooltip></el-table-column>
            <el-table-column prop="cardNumber" v-if="false" ></el-table-column>
            <el-table-column prop="cardNumberNone" label="身份证号" width="210" show-overflow-tooltip></el-table-column>
            <el-table-column prop="houseId" v-if="false"></el-table-column>
            <el-table-column prop="roleId" v-if="false"></el-table-column>
            <el-table-column prop="userId" v-if="false"></el-table-column>
            <el-table-column prop="imgPath" v-if="false"></el-table-column>
            <el-table-column prop="communityName" label="所属小区" width="100" show-overflow-tooltip></el-table-column>
            <el-table-column prop="buildingName" label="所属楼宇" width="80" show-overflow-tooltip></el-table-column>
            <el-table-column prop="unitName" label="所属单元" width="80" show-overflow-tooltip></el-table-column>
            <el-table-column prop="houseName" label="所属房屋" width="80" show-overflow-tooltip></el-table-column>
            <el-table-column prop="relationName" label="关系" show-overflow-tooltip></el-table-column>
            <el-table-column prop="address" label="户籍所在地" width="140" show-overflow-tooltip></el-table-column>
            <el-table-column prop="roleName" label="所属角色" show-overflow-tooltip></el-table-column>
            <el-table-column label="操作" width="255" fixed="right" v-if="edit_authority">
              <template slot-scope="scope" >
                <el-button size="mini" @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
                <el-button type="success" size="mini" @click="icInfoAdd(scope.$index, scope.row)">IC信息维护</el-button>
                <el-button type="danger" size="mini" @click="handleDel(scope.$index, scope.row)">删除</el-button>
                <!--<el-button type="success" size="mini" @click="handleDel(scope.$index, scope.row)">关联房屋</el-button>-->
              </template>
            </el-table-column>
          </el-table>

          <!--工具条-->
          <el-col :span="24" class="toolbar" id="pageDiv">
            <el-pagination small background :current-page="page" @current-change="handleCurrentChange" @size-change="handleSizeChange" :page-sizes="[10, 20, 50, 100]" :page-size="pageSize" :total="total" layout="total,sizes, prev, pager, next" style="float:right;"></el-pagination>
          </el-col>

          <!--编辑界面-->
          <el-dialog title="编辑" :visible.sync="editFormVisible" :close-on-click-modal="false" @close="resetForm('editForm')">
            <el-form :model="editForm" label-width="100px" :rules="addFormRules" ref="editForm" size="mini">
              <el-input v-model="editForm.houseId" type="hidden" style="display: none!important;"></el-input>
              <el-input v-model="editForm.roleId" type="hidden" style="display: none!important;"></el-input>
              <el-input v-model="editForm.userId" type="hidden" style="display: none!important;"></el-input>
              <el-col :span="12">
                <el-form-item label="姓名" prop="name">
                  <el-input v-model="editForm.name" auto-complete="off" placeholder="请输入姓名"></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="手机号" prop="phone">
                  <el-input v-model="editForm.phone" auto-complete="off" placeholder="请输入手机号"></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="身份证号" prop="cardNumber">
                  <el-input v-model="editForm.cardNumber" auto-complete="off" placeholder="请输入身份证号"></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="户籍所在地" prop="address">
                  <el-input v-model="editForm.address" auto-complete="off" placeholder="请输入户籍所在地"></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="性别" prop="sex">
                  <el-radio-group v-model="editForm.sex">
                    <el-radio label="0">男</el-radio>
                    <el-radio label="1">女</el-radio>
                  </el-radio-group>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="所属房屋" prop="houseName">
                  <el-autocomplete popper-class="my-autocomplete" v-model="editForm.houseName" :fetch-suggestions="querySearch" placeholder="请输入内容" size="mini" style="width: 100%" @select="handleSelect">
                    <i class="el-icon-edit el-input__icon" slot="suffix">
                    </i>
                    <template slot-scope="{ item }">
                      <div class="name" style="display: none;">{{ item.houseId }}</div>
                      <span class="addr">{{ item.communityName }}{{ item.buildingName }}{{ item.unitName }}{{ item.houseName }}</span>
                    </template>
                  </el-autocomplete>
                </el-form-item>
              </el-col>
              <el-col :span="24">
                <el-form-item label="所属角色" prop="roleName">
                  <el-input v-model="editForm.roleName" size="medium" disabled class="input-with-select">
                    <el-button slot="append" icon="el-icon-search" @click.native="showRoleSelect"></el-button>
                  </el-input>
                  <!--<el-autocomplete popper-class="my-autocomplete"
                                   v-model="editForm.roleName"
                                   :fetch-suggestions="querySearchRole"
                                   placeholder="请输入角色名称"
                                   size="mini"
                                   style="width: 100%"
                                   @select="handleSelectRole">
                    <i class="el-icon-edit el-input__icon"
                       slot="suffix">
                    </i>
                    <template slot-scope="{ item }">
                      <div class="name"
                           style="display: none;">{{ item.roleId }}</div>
                      <span class="addr">{{ item.roleName }}</span>
                    </template>
                  </el-autocomplete>-->
                </el-form-item>
              </el-col>
            </el-form>
            <div slot="footer" class="dialog-footer">
              <el-button @click.native="editFormVisible = false">取消</el-button>
              <el-button type="primary" @click.native="editSubmit" :loading="editLoading">提交</el-button>
              <!--<el-button type="primary" @click="resetForm('editForm')">重置</el-button>-->
            </div>
          </el-dialog>

          <!--新增界面-->
          <el-dialog title="新增" :visible.sync="addFormVisible" :close-on-click-modal="false" @close="resetForm('addForm')">
            <el-form :model="addForm" label-width="100px" :rules="addFormRules" ref="addForm" size="mini">
              <el-input v-model="addForm.houseId" type="hidden" style="display: none!important;"></el-input>
              <el-input v-model="addForm.roleId" type="hidden" style="display: none!important;"></el-input>
              <el-col :span="12">
                <el-form-item label="姓名" prop="name">
                  <el-input v-model="addForm.name" auto-complete="off" placeholder="请输入姓名"></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="手机号" prop="phone">
                  <el-input v-model="addForm.phone" auto-complete="off" placeholder="请输入手机号"></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="身份证号" prop="cardNumber">
                  <el-input v-model="addForm.cardNumber" auto-complete="off" placeholder="请输入身份证号"></el-input>
                </el-form-item>
              </el-col>

              <el-col :span="12">
                <el-form-item label="户籍所在地" prop="address">
                  <el-input v-model="addForm.address" auto-complete="off" placeholder="请输入户籍所在地"></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="性别" prop="sex">
                  <el-radio-group v-model="addForm.sex">
                    <el-radio label="0">男</el-radio>
                    <el-radio label="1">女</el-radio>
                  </el-radio-group>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="所属房屋" prop="houseName">
                  <el-autocomplete popper-class="my-autocomplete" v-model="addForm.houseName" :fetch-suggestions="querySearch" placeholder="请输入房屋名称" size="mini" style="width: 100%" @select="handleSelect">
                    <i class="el-icon-edit el-input__icon" slot="suffix">
                    </i>
                    <template slot-scope="{ item }">
                      <div class="name" style="display: none;">{{ item.houseId }}</div>
                      <span class="addr">{{ item.communityName }}{{ item.buildingName }}{{ item.unitName }}{{ item.houseName }}</span>
                    </template>
                  </el-autocomplete>
                </el-form-item>
              </el-col>
              <el-col :span="24">
                <el-form-item label="所属角色" prop="roleName">
                  <el-input v-model="addForm.roleName" size="medium" disabled class="input-with-select">
                    <el-button slot="append" icon="el-icon-search" @click.native="showRoleSelect"></el-button>
                  </el-input>
                  <!--<el-autocomplete popper-class="my-autocomplete"
                                   v-model="addForm.roleName"
                                   :fetch-suggestions="querySearchRole"
                                   placeholder="请输入角色名称"
                                   size="mini"
                                   style="width: 100%"
                                   @select="handleSelectRole">
                    <i class="el-icon-edit el-input__icon"
                       slot="suffix">
                    </i>
                    <template slot-scope="{ item }">
                      <div class="name"
                           style="display: none;">{{ item.roleId }}</div>
                      <span class="addr">{{ item.roleName }}</span>
                    </template>
                  </el-autocomplete>-->
                </el-form-item>
              </el-col>

            </el-form>
            <div slot="footer" class="dialog-footer">
              <el-button @click.native="addFormVisible = false">取消</el-button>
              <el-button type="primary" @click.native="addSubmit" :loading="addLoading">提交</el-button>
              <!--<el-button type="primary" @click="resetForm('addForm')">重置</el-button>-->
            </div>
          </el-dialog>

          <!--IC信息维护界面-->
          <el-dialog title="IC信息维护" width="50%" :visible.sync="addIcInfoFormVisible" :close-on-click-modal="false">
            <avue-crud :option="guardOption" ref="crud" v-model="guardForm" :page="guardPage" :data="guardData" :table-loading="guardLoading" :before-open="beforeOpen" :before-close="beforeClose" @refresh-change="refreshChange" @search-change="searchChange" @current-change="currentChange" @row-del="rowDel" @row-save="rowSave">
              <template slot-scope="scope" slot="icIdForm">
                <avue-crud-input v-model="guardForm.icId" :disabled="scope.column.disabled" :placeholder="scope.column.placeholder"></avue-crud-input>
              </template>
              <!-- <template slot="menuLeft"
                        class="fengniao-crud-header">
                <el-button type="primary"
                           size="small">测试</el-button>
              </template> -->
              <template slot-scope="scope" slot="menu">
                <el-button @click="syncIC(scope.$index, scope.row)" size="small" type="primary" plain>同步</el-button>
                <el-button @click="$refs.crud.rowDel(scope.row,scope.$index )" size="small" type="danger" plain>删除</el-button>
              </template>
              <template slot-scope="scope" slot="status">
                <el-tag v-if="Number(scope.row.status)===0" type="warning">{{scope.label}}</el-tag>
                <el-tag v-else-if="Number(scope.row.status)===1" type="success">{{scope.label}}</el-tag>
                <el-tag v-else-if="Number(scope.row.status)===2" type="danger">{{scope.label}}</el-tag>
                <el-tag v-else-if="Number(scope.row.status)===3" type="warning">{{scope.label}}</el-tag>
              </template>
            </avue-crud>

          </el-dialog>

          <!--导入界面-->
          <el-dialog title="导入" :visible.sync="importFormVisible" :close-on-click-modal="false">
            <el-upload class="upload-demo" ref="upload" accept="xls,xlsx" action="/admin/houseOwner/upload" :on-preview="handlePreview" :on-remove="handleRemove" :on-success="handleSuccess" :before-upload="beforeAvatarUpload" :file-list="fileList" :headers="building_uploadHeader" :data="uploadParams" :auto-upload="false">
              <el-button slot="trigger" size="small" type="primary">选取文件</el-button>
              <el-button style="margin-left: 10px;" size="small" type="success" @click="submitUpload" :loading="addLoading">上传</el-button>
              <div slot="tip" class="el-upload__tip">只能上传xls/xlsx文件</div>
            </el-upload>
          </el-dialog>
          <!--角色选择界面-->
          <el-dialog title="门禁角色选择" :visible.sync="roleSelectVisible" :close-on-click-modal="false">
            <div style="height: 380px!important;position:relative">
              <div style="height: 260px;overflow: auto;">
                <roleTree ref="role_tree" @treeNode-click="roleTreeNodeClick"></roleTree>
              </div>
              <div>
                <el-tag type="info" style="position:absolute;bottom: 95px;" size="small">选择的角色</el-tag>
              </div>
              <el-input type="textarea" style="position:absolute;bottom: 0px;" disabled :rows="4" v-model="textarea_role"></el-input>
            </div>
            <div slot="footer" class="dialog-footer">
              <el-button @click.native="roleSelectVisible = false">取消</el-button>
              <el-button type="primary" @click.native="roleSelectSubmit" :loading="addLoading">确定</el-button>
            </div>
          </el-dialog>
        </div>
      </el-main>
    </el-container>

  </div>
</template>
<style lang="scss" scoped>
.my-autocomplete {
  li {
    line-height: normal;
    padding: 7px;
    .name {
      text-overflow: ellipsis;
      overflow: hidden;
    }
    .addr {
      font-size: 12px;
      color: #b4b4b4;
    }
    .highlighted .addr {
      color: #ddd;
    }
  }
}
</style>

<script>
import {
  fetchIcList,
  addIcObjByHouseOwnerId,
  putIcObj,
  delIcObj,
  updateIcObj
} from '@/api/guard/'
import { getToken, setToken, removeToken } from '@/util/auth'
import {mapGetters} from "vuex";
import request from '@/router/axios'
import buildingTree from '../building/buildingTree.vue'
import roleTree from '../houseowner/roleTree.vue'
export default {
  name: 'table_house_owner',
  components: {
    buildingTree,
    roleTree
  },
  data() {
    return {
      guardId: '',
      code: 0,
      guardForm: {},
      textarea_role: '',
      textarea_role_arr: [],
      textarea_role_arr_des: [],
      edit_authority:false,
      guardLoading: false,
      guardPage: {
        total: 0, // 总页数
        currentPage: 1, // 当前页数
        pageSize: 10 // 每页显示多少条
      },
      rfidreader: undefined,
      guardOption: {
        index: true,
        border: true,
        stripe: true,
        height: 300,
        editBtn: false,
        indexLabel: '序号',
        formWidth: '30%',
        menuAlign: 'center',
        delBtn: false,
        // menuWidth: 350,
        column: [
          {
            label: 'IC信息',
            sortable: true,
            size: 'small',
            span: 24,
            prop: 'icId',
            disabled: true,
            formsolt: true,
            placeholder: '请刷卡IC的卡号',
            rules: [
              {
                required: true,
                message: '请输入IC信息',
                trigger: 'blur'
              }
            ]
          },
          {
            label: '设备名称',
            sortable: true,
            size: 'small',
            span: 24,
            addVisdiplay: false,
            editVisdiplay: false,
            prop: 'deviceName'
          },
          {
            label: '状态',
            sortable: true,
            size: 'small',
            type: 'select',
            addVisdiplay: false,
            editVisdiplay: false,
            prop: 'status',
            solt: true,
            dicData: [
              {
                label: '同步中',
                value: '0'
              },
              {
                label: '同步成功',
                value: '1'
              },
              {
                label: '同步失败',
                value: '2'
              },
              {
                label: '删除中',
                value: '3'
              },
              {
                label: '欠费已停用',
                value: '4'
              }
            ]
          }
        ]
      },
      guardData: [],
      filters: {
        name: '',
        phone: ''
      },
      url: {
        list: '/admin/houseOwner/page',
        del: '/admin/houseOwner/doDel',
        batchDel: '/admin/houseOwner/doBatchDel',
        save: '/admin/houseOwner/doAdd',
        edit: '/admin/houseOwner/doUpdate'
      },
      communityBuildings: [],
      restaurantsHouses: [],
      restaurantsRoles: [],
      icinfos: [],
      houseVisible: false,
      unitVisible: false,
      buildingVisible: true,
      importDisabled: true,
      roleSelectVisible: false,
      addDisabled: true,
      default_expended_key: [],
      fileList: [],
      total: 0,
      page: 1,
      pageSize: 10,
      sort: {
        sort: 'sort',
        order: 'asc'
      },
      listLoading: false,
      sels: [], // 列表选中列
      uploadParams: {},
      editFormVisible: false, // 编辑界面是否显示
      importFormVisible: false,
      editLoading: false,
      addFormVisible: false, // 新增界面是否显示
      addLoading: false,
      addIcInfoFormVisible: false, // IC信息维护界面是否显示
      addIcInfoLoading: false,
      addFormRules: {
        name: [
          {
            required: true,
            message: '请输入姓名'
          }
        ],
        cardNumber: [
          {
            required: false,
            message: '请输入身份证号'
          },
          {
            pattern: /^[1-9]{1}[0-9]{14}$|^[1-9]{1}[0-9]{16}([0-9]|[xX])$/,
            message: '身份证格式不正确'
          }
        ],
        sex: [
          {
            required: false,
            message: '请选择性别'
          }
        ],
        phone: [
          {
            required: false,
            message: '请输入手机号码'
          },
          {
            pattern: /^1[3|4|5|6|7|8|9][0-9]\d{8}$/,
            message: '手机号码格式不正确'
          }
        ],
        address: [
          {
            required: false,
            message: '请输入地址'
          }
        ],
        houseName: [
          {
            required: true,
            message: '请选择所属房屋'
          }
        ]
      },
      // 新增界面数据
      addForm: {
        name: '',
        cardNumber: '',
        sex: '',
        phone: '',
        address: '',
        houseName: ''
      },
      // 编辑页面数据
      editForm: {
        name: '',
        cardNumber: '',
        sex: '',
        phone: '',
        address: '',
        houseName: ''
      },
      addIcInfoForm: {},
      formFile: {},
      buildingTreeData: [],
      defaultProps: {
        children: 'children',
        label: 'name'
      },
      // 数据字典
      propertyRightOptions: [],
      building_uploadHeader: {
        Authorization: 'Bearer ' + getToken()
      }
    }
  },
  methods: {
    initCardId() {
      try {
        this.rfidreader = window.YOWORFIDReader.createNew()
      } catch (e) {
        this.$message.error('创建友我科技RFID云服务连接失败，请先下载安装！')
        top.location =
          'http://www.youwokeji.com.cn/CloudReader/YOWORFIDReaderCloudForWeb.exe'
      }
      if (!this.rfidreader.TryConnect()) {
        this.$message.error('浏览器不支持')
      }
      var FormatID = '0'
      var OrderID = '0'
      this.rfidreader.Repeat = 0
      this.rfidreader.HaltAfterSuccess = 1
      this.rfidreader.M1WriteBlock(4, this.code, FormatID)
      // this.rfidreader.RequestTypeACardNo(FormatID, OrderID)
      this.rfidreader.onResult(resultdata => {
        switch (resultdata.FunctionID) {
          case 6:
            if (resultdata.Result > 0) {
              this.guardForm.icId = resultdata.CardNo
              this.$message.success('读取成功')
            } else {
              this.$message.success('读取失败，请先放置IC卡')
            }
            break
        }
      })
    },
    getIcList() {
      this.guardLoading = true
      fetchIcList(this.guardId, {
        page: this.guardPage.currentPage,
        limit: this.guardPage.pageSize
      }).then(response => {
        this.guardLoading = false
        this.guardData = response.data.data.records
        this.guardPage.total = response.data.data.total
      })
    },
    currentChange(val) {
      this.guardPage.page = val
      this.getIcList()
    },
    refreshChange(val) {
      this.getIcList()
      this.$message({
        showClose: true,
        message: '刷新成功',
        type: 'success'
      })
    },
    searchChange(val) {
      console.log(val)
    },
    rowAdd() {
      this.$refs.crud.rowAdd()
    },
    beforeOpen(show) {
      this.initCardId()
      show()
    },
    beforeClose(done) {
      var FormatID = '0'
      var OrderID = '0'
      this.rfidreader.Repeat = 0
      //this.rfidreader.RequestTypeACardNo(FormatID, OrderID)
      done()
    },
    rowDel(row, index) {
      this.$confirm('是否确认删除', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          return delIcObj(row)
        })
        .then(data => {
          this.$message({
            showClose: true,
            message: '删除成功',
            type: 'success'
          })
          this.getIcList()
          //this.guardData.splice(index, 1);
        })
        .catch(function(err) {})
    },
    rowSave(row, done) {
      addIcObjByHouseOwnerId(
        Object.assign({}, row, { houseOwnerId: this.guardId })
      ).then(data => {
        this.$message({
          showClose: true,
          message: data.data.msg,
          type: 'success'
        })
        this.getIcList()
        //this.guardData.push(index, 1);
        var FormatID = '0'
        var OrderID = '0'
        this.rfidreader.Repeat = 0
        //this.rfidreader.RequestTypeACardNo(FormatID, OrderID)
        done()
      })
    },
    syncIC(index, row) {
      updateIcObj(row).then(data => {
        this.$message({
          showClose: true,
          message: '同步中',
          type: 'success'
        })
        this.getIcList()
      })
    },
    handleSortChange(sort) {
      this.sort = {
        sort: sort.prop,
        order: sort.order == 'ascending' ? 'asc' : 'desc'
      }
      this.getCommunityBuildings()
    },

    handleDownFile(type, filePath) {
      var downUrl = this.url.downFile + '?down=' + type + '&dbPath=' + filePath
      window.open(downUrl)
    },
    tableRowClassName(row, index) {
      // 把每一行的索引放进row
      row.index = row.rowIndex
    },
    headStyle({ row, rowIndex }) {
      return 'table_head_style'
    },
    index_formatter: function(row, column, cellValue, index) {
      // 放回索引值
      return this.pageSize * (this.page - 1) + 1 + index
    },
    handleCurrentChange(val) {
      this.page = val
      this.getCommunityBuildings()
    },
    handleSizeChange(val) {
      this.pageSize = val
      this.page = 1
      this.getCommunityBuildings()
    },
    resetForm(formName) {
      this.$refs[formName].resetFields()
      this.textarea_role_arr = []
      this.textarea_role = ''
      this.textarea_role_arr_des = []
    },
    resetSearchForm(formName) {
      this.filters = {
        name: '',
        phone: ''
      }
    },

    // 获取用户列表
    getCommunityBuildings(flag) {
      // 获取当前树节点选中小区
      var data = this.$refs.building_tree.$refs.tree.getCurrentNode()
      var node = this.$refs.building_tree.$refs.tree.getNode(data.id)
      var communityId = ''
      var buildingId = ''
      var unitId = ''
      if(flag){
					this.page = 1;
				}
      if (node.level == 1) {
        communityId = data.id
      } else if (node.level == 2) {
        buildingId = data.id
      } else {
        unitId = data.id
      }
      const para = {
        params: {
          page: this.page,
          limit: this.pageSize,
          // 排序
          orderByField: this.sort.sort,
          isAsc: this.sort.order,
          name: this.filters.name,
          phone: this.filters.phone,
          communityId: communityId,
          buildingId: buildingId,
          unitId: unitId
        }
      }
      this.listLoading = true
      request.get(this.url.list, para).then(res => {
        this.total = res.data.total
        var datas = res.data.records
        this.communityBuildings = datas
        this.listLoading = false
      })
    },
    // 删除
    handleDel: function(index, row) {
      this.$confirm('确认删除该记录吗?', '提示', {
        type: 'warning'
      })
        .then(() => {
          this.listLoading = true
          const para = {
            id: row.id
          }
          request
            .get(this.url.del, {
              params: para
            })
            .then(res => {
              this.listLoading = false
              this.$message({
                message: '删除成功',
                type: 'success',
                duration: 1500
              })
              this.getCommunityBuildings()
            })
        })
        .catch(() => {})
    },
    // 显示编辑界面
    handleEdit: function(index, row) {
      this.editFormVisible = true
      this.editForm = Object.assign({}, row)
      this.formFile = {}
      this.getHouseData()
      this.textarea_role = this.editForm.roleName
      if (this.editForm.roleName && this.editForm.roleName.length > 0) {
        var roleNames = this.editForm.roleName.split(',')
        var roleIds = this.editForm.roleId.split(',')
        for (var i = 0; i < roleNames.length; i++) {
          this.textarea_role_arr.push(roleIds[i])
          this.textarea_role_arr_des.push(roleNames[i] + '@' + roleIds[i])
        }
      }
    },
    // 显示新增界面
    handleAdd: function() {
      this.addFormVisible = true
      this.formFile = {}
      this.getHouseData()
    },
    // 显示IC信息维护界面
    icInfoAdd: function(index, row) {
      this.guardId = row.id
      this.getIcList()
      this.addIcInfoFormVisible = true
    },
    // 编辑
    editSubmit: function() {
      this.$refs.editForm.validate(valid => {
        if (valid) {
          this.$confirm('确认提交吗？', '提示', {}).then(() => {
            this.editLoading = true
            const para = Object.assign({}, this.editForm)
            request.post(this.url.edit, para).then(res => {
              if (res.data.success) {
                this.editLoading = false
                this.$message({
                  message: '提交成功',
                  type: 'success',
                  duration: 1500
                })
                this.$refs['editForm'].resetFields()
                this.editFormVisible = false
                this.getCommunityBuildings()
              } else {
                this.$message.error(res.data.msg)
              }
              this.editLoading = false
            })
          })
        }
      })
    },
    showRoleSelect: function() {
      this.roleSelectVisible = true
    },
    roleSelectSubmit: function() {
      if (this.addFormVisible) {
        this.addForm.roleId = this.textarea_role_arr.join()
        this.addForm.roleName = this.textarea_role
      } else {
        this.editForm.roleId = this.textarea_role_arr.join()
        this.editForm.roleName = this.textarea_role
      }
      this.roleSelectVisible = false
    },
    // 新增
    addSubmit: function() {
      this.$refs.addForm.validate(valid => {
        if (valid) {
          this.$confirm('确认提交吗？', '提示', {}).then(() => {
            this.addLoading = true
            const communityBuilding = Object.assign({}, this.addForm)
            request.post(this.url.save, communityBuilding).then(res => {
              if (res.data.success) {
                this.$message({
                  message: '提交成功',
                  type: 'success',
                  duration: 1500
                })
                this.$refs['addForm'].resetFields()
                this.addFormVisible = false
                this.getCommunityBuildings()
              } else {
                this.$message.error(res.data.msg)
              }
              this.addLoading = false
            })
          })
        }
      })
    },
    selsChange: function(sels) {
      this.sels = sels
    },

    // 模板下载
    templeteDown: function() {
      location.href = '/static/templates/owner.xls'
    },
    // 模板上传
    templeteUp: function() {
      this.fileList = []
      this.uploadParams = {
        communityId: this.$refs.building_tree.$refs.tree.getCurrentKey()
      }
      this.importFormVisible = true
    },
    submitUpload() {
    	if(this.$refs.upload.uploadFiles.length==0){
	    		this.$message({ message: "请先选择上传的文件。",type: 'info',duration: 2000});
	    		return;
	    	}
      this.addLoading = true
      this.$refs.upload.submit()
    },
    handleRemove(file, fileList) {
      console.log(file, fileList)
    },
    handlePreview(file) {
      console.log(file)
    },
    handleSuccess(response, file, fileList) {
      this.addLoading = false
      if (!response.success) {
        this.$message.error(response.msg)
      } else {
        this.$message({
          message: response.msg,
          type: 'success',
          duration: 3000
        })
      }
      this.fileList = []
      this.importFormVisible = false
      // 刷新列表
      this.getCommunityBuildings()
    },
    beforeAvatarUpload(file) {
      const isXls = file.type === 'application/vnd.ms-excel'
      const isXlsx =
        file.type ===
        'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
      if (!isXls && !isXlsx) {
        this.$message.error('格式不正确!')
      }

      return isXls || isXlsx
    },

    // 批量删除
    batchRemove: function() {
      var ids = this.sels.map(item => item.id).toString()
      this.$confirm('确认删除选中记录吗？', '提示', {
        type: 'warning'
      })
        .then(() => {
          this.listLoading = true
          const para = {
            ids: ids
          }
          request
            .get(this.url.batchDel, {
              params: para
            })
            .then(res => {
              this.listLoading = false
              this.$message({
                message: '删除成功',
                type: 'success',
                duration: 1500
              })
              this.getCommunityBuildings()
            })
        })
        .catch(() => {})
    },

    // 初始化数据字典
    initDictsData: function() {
      request.get('/admin/dict/type/log_type').then(res => {
        if (res.status === 200) {
          this.propertyRightOptions = res.data
        }
      })
    },

    // 初始化树
    loadChildrenNode(node, resolve) {
      if (node.level === 0) {
        request.get('/admin/community?getCommunitysByCurrentUser').then(res => {
          if (res.status === 200) {
            defaultNode = res.data[0].id
            this.$refs.tree.setCurrentKey(defaultNode)
            return resolve(res.data)
          }
        })
      } else if (node.level === 1) {
        // 点击小区节点，加载该小区下的楼宇信息
        request
          .get('/admin/communityBuilding/getCommunityBuildings/' + node.key)
          .then(res => {
            if (res.status === 200) {
              return resolve(res.data)
            }
          })
      } else if (node.level === 2) {
        // 点击小区节点，加载该楼宇下的单元信息
        request
          .get('/admin/communityBuilding/getBuildingUnits/' + node.key)
          .then(res => {
            if (res.status === 200) {
              return resolve(res.data)
            }
          })
      } else {
        return resolve([])
      }
    },
    treeNodeClick(data, node) {
      this.addDisabled = false
      this.restaurantsHouses = []
      this.restaurantsRoles = []
      if (node.level == 1) {
        this.importDisabled = false
      } else {
        this.importDisabled = true
      }
      this.getCommunityBuildings(true);
      this.resetSearchForm();
    },
    roleTreeNodeClick(data, node) {
      if (data.type == 'role') {
        var index = -1
        for (var i = 0; i < this.textarea_role_arr_des.length; i++) {
          if (this.textarea_role_arr_des[i] == data.name + '@' + data.id) {
            index = i
            break
          }
        }

        if (index >= 0) {
          this.textarea_role_arr_des.splice(index, 1)
        } else {
          this.textarea_role_arr_des.push(data.name + '@' + data.id)
        }
        var textarea_role_arr_name = []
        this.textarea_role_arr = []
        for (var i = 0; i < this.textarea_role_arr_des.length; i++) {
          var fg = this.textarea_role_arr_des[i].split('@')
          this.textarea_role_arr.push(fg[1])
          textarea_role_arr_name.push(fg[0])
        }

        this.textarea_role = textarea_role_arr_name.join()
      }
    },
    querySearch(queryString, cb) {
      var restaurants = this.restaurantsHouses
      var results = queryString
        ? restaurants.filter(this.createFilter(queryString))
        : restaurants
      // 调用 callback 返回建议列表的数据
      cb(results)
    },
    createFilter(queryString) {
      return restaurant => {
        return (
          restaurant.houseName
            .toLowerCase()
            .indexOf(queryString.toLowerCase()) === 0
        )
      }
    },

    handleSelect(item) {
      if (this.addFormVisible) {
        this.addForm.houseId = item.id
        this.addForm.houseName = item.houseName
      } else {
        this.editForm.houseId = item.id
        this.editForm.houseName = item.houseName
      }
    },
    handleSelectRole(item) {
      if (this.addFormVisible) {
        this.addForm.roleId = item.roleId
        this.addForm.roleName = item.roleName
      } else {
        this.editForm.roleId = item.roleId
        this.editForm.roleName = item.roleName
      }
    },
    querySearchRole(queryString, cb) {
      var restaurants = this.restaurantsRoles
      var results = queryString
        ? restaurants.filter(this.createFilterRole(queryString))
        : restaurants
      // 调用 callback 返回建议列表的数据
      cb(results)
    },
    createFilterRole(queryString) {
      return restaurant => {
        return (
          restaurant.roleName
            .toLowerCase()
            .indexOf(queryString.toLowerCase()) === 0
        )
      }
    },
    getHouseData() {
      // 获取当前树节点选中小区
      var data = this.$refs.building_tree.$refs.tree.getCurrentNode()
      var node = this.$refs.building_tree.$refs.tree.getNode(data.id)
      var communityId = ''
      var buildingId = ''
      var unitId = ''
      if (node.level == 1) {
        communityId = data.id
      } else if (node.level == 2) {
        buildingId = data.id
      } else {
        unitId = data.id
      }
      var para = {
        params: {
          communityId: communityId,
          buildingId: buildingId,
          unitId: unitId
        }
      }
      // 加载房屋信息
      request.get('/admin/houseOwner/queryUnitHouse', para).then(res => {
        if (res.status === 200) {
          this.restaurantsHouses = res.data
        }
      })
      // 加载角色信息
      //    request.get('/admin/role/queryRole', para).then(res => {
      //      if (res.status === 200) {
      //        this.restaurantsRoles = res.data
      //      }
      //    })
    }
    // 树相关方法结束
  },
  computed: {
      ...mapGetters(["permissions"])
   },
   created() {
      this.edit_authority = this.permissions["edit_authority"];
    },
  mounted() {
    // 加载楼房树
    this.initDictsData()
  }
}
</script>

</html>